<template>
	<view>
		<view v-if='banner && banner.length > 0'>
			<u-swiper :list="banner" radius='0' height='158px'></u-swiper>
		</view>
		<view>  
			<u-cell-group>
				<u-cell icon="home" title="书剑古茶" value="门店列表" :isLink='true'
					@click='toUrl("/pages/index/stores")'></u-cell>
			</u-cell-group>
		</view>
		<view v-if='activities && activities.length > 0'>
			<u-divider text="热门活动"></u-divider>
			<view v-for='item in activities' class='activity-list'
				@click='toUrl(`/pages/index/activity?id=${item.id}`)'>
				<view style='width:100%'>
					<u--image :src='item.image' width='100%'></u--image>
				</view>
				<view class='title'>
					{{item.title}}
				</view>
				<view class='date'>
					{{$u.timeFormat(new Date(item.startTime), 'yyyy年mm月dd日')}}开始
				</view>
			</view>
		</view>
		<view v-if='products && products.length > 0'>
			<u-divider text="主推产品"></u-divider>
			<view style='display: flex;flex-wrap: wrap;width:100%'>
				<view v-for='(item,index) in products' class='product-list' :key='index'>
					<view>
						<view style='background-color: #f3f3f3;border-radius: 5px;margin:5px;padding:10px'>
							<view class='image-container'>
								<image v-if='item.cover == null' :src="defaultImage" class='image-a'></image>
								<image v-else :src="item.cover" class='image-a'></image>
							</view>
							<view class='product-name'>
								{{item.name}}
							</view>
							<view>
								<u-row>
									<u-col span='6'>
										<view>
											<text class='price'>￥{{item.specifications[0].price}}</text>
										</view>
									</u-col>
									<u-col span='6' v-if='item.specifications && item.specifications.length == 1'>
										<view>
											<view v-if='item.quantity > 0'>
												<u-row>
													<u-col span='4'>
														<view class="minus" @click='pev(index)'>
															<u-icon name="minus" size="12"></u-icon>
														</view>
													</u-col>
													<u-col span='4'>
														<view style="text-align: center;" class="input">
															{{item.quantity}}
														</view>
													</u-col>
													<u-col span='4'>
														<view class="plus" @click='add(index)'>
															<u-icon name="plus" color="#FFFFFF" size="12"></u-icon>
														</view>
													</u-col>
												</u-row>
											</view>
											<view v-else>
												<u-row>
													<u-col span='4'>
														<view>
														</view>
													</u-col>
													<u-col span='4'>
														<view style="text-align: center;" class="input">
														</view>
													</u-col>
													<u-col span='4'>
														<view class="plus" @click='add(index)'>
															<u-icon name="plus" color="#FFFFFF" size="12"></u-icon>
														</view>
													</u-col>
												</u-row>
											</view>
										</view>
									</u-col>
									<u-col v-else span='6'>
										<view style='text-align: right;'>
											<text class='spec-btn' @click='chooseProduct(item)'>选规格</text>
										</view>
									</u-col>
								</u-row>
							</view>
						</view>
					</view>
				</view>

			</view>
		</view>
		<!-- 弹出需要选择的标签 -->
		<u-popup v-if='chooseProduct != ""' :show="showTag" @close="showTag = false" mode='bottom' round='10'>
			<view style='max-height: 65vh;padding: 20px 10px 30px 10px;overflow: auto;'>
				<u-divider :text="choosedProduct.name"></u-divider>
				<view>
					<view class="container">
						<view class="item" v-for='item in choosedProduct.specifications'>
							<view v-if='choosedSpec.id == item.id' class='spec-active'>
								{{item.name}}
							</view>
							<view v-else class='spec' @click='choosedSpec = item'>{{item.name}}</view>
						</view>
					</view>
				</view>
				<view style='padding:10px'>
					<u-row>
						<u-col span='6'>
							<view style='color:#ff9900'>
								￥{{choosedSpec.price}}
							</view>
						</u-col>
						<u-col span='6'>
							<view style='float: right;'>
								<u-number-box v-model="quantity">
									<view slot="minus" class="minus">
										<u-icon name="minus" size="12"></u-icon>
									</view>
									<text slot="input" style="width: 50px;text-align: center;"
										class="input">{{quantity}}</text>
									<view slot="plus" class="plus">
										<u-icon name="plus" color="#FFFFFF" size="12"></u-icon>
									</view>
								</u-number-box>
							</view>
						</u-col>
					</u-row>
				</view>
				<view style='padding-top:10px'>
					<u-button text='加入购物车' type='primary' @click='addSpec'></u-button>
				</view>
			</view>
		</u-popup>
	</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				banner: [],
				products: [],
				defaultImage: 'https://picture.jmgc.vip/4c0ca142-9573-4e44-999d-545f2c244c0d.png',
				activities: [],
				showTag: false,
				choosedProduct: '',
				choosedSpec: '',
				quantity: 1,
				store: '',
				carts: []
			}
		},
		onShow() {
			// 判断是否登录，登录了的，判断是否已经有openid，无的，获取一次
			let token = uni.getStorageSync('api_token')
			if (token != '') {
				this.request.get(`api/user`).then((res) => {
					console.log('用户信息', res.data)
					if (res.data.wechatOpenId == null || res.data.wechatOpenId == '') {
						let _this = this
						uni.login({
							provider: "weixin",
							success: function(res) {
								let data = {
									code: res.code
								}
								_this.request.get("wechat/mini/login-info", data).then((res) => {
									if (res.data.data.openid) {
										_this.wechatOpenId = res.data.data.openid
										_this.request.put(
												`api/user/set/wechatOpenId/${_this.wechatOpenId}`
												)
											.then((res) => {
												console.log('绑定成功')
											})
									}
								})
							},
						});
					}
				})
			}
			let store = uni.getStorageSync('store')
			if (store == '') {
				this.request.get(`public/stores`).then((res) => {
					console.log('store', res.data)
					this.store = res.data[0]
				})
			} else {
				this.store = store
			}
			let carts = uni.getStorageSync('carts')
			if (carts != '') {
				this.carts = carts
				uni.setTabBarBadge({
					index: 2,
					text: `${carts.length}`
				})
			} else {
				uni.removeTabBarBadge({
					index: 2
				})
			}
		},
		onLoad() {
			this.getHotProduct()
			this.getBanner()
			this.getActivity()
			this.getAuthorizeInfo()
		},
		methods: {
			getBanner() {
				this.request.get(`public/albums`, {
					'@filter': `entity.getType() == 'index-banner'`
				}).then((res) => {
					let banner = []
					for (let i of res.data[0].pictures) {
						banner.push(i)
					}
					this.banner = banner
				})
			},
			getHotProduct() {
				uni.showLoading()
				this.request.get(`public/products`, {
					'@filter': `entity.getIsHot() == true && entity.getIsOnSale() == true`,
					'@display': ['name', 'cover', 'specifications']
				}).then((res) => {
					if (res.data.length < this.limit) {
						this.status = 'nomore'
					}
					let carts = uni.getStorageSync('carts')
					for (let i of res.data) {
						i['quantity'] = 0
						if (carts != '') {
							for (let c of carts) {
								if (c.specId == i.specifications[0].id) {
									i['quantity'] = c.quantity
								}
							}
						}
						this.products.push(i)
						uni.hideLoading()
					}
					console.log('product', this.products)
				})
			},
			getActivity() {
				let date = new Date()
				const today =
					`${date.getFullYear()}/${date.getMonth() + 1}/${date.getDate()} ${date.getHours()}:${date.getMinutes()}`
				this.request.get(`public/activities`, {
					'@filter': `entity.getEnabled() == true && entity.getStartTime() > datetime.get('${today}')`
				}).then((res) => {
					console.log('activity', res.data)
					this.activities = res.data
				})
			},
			toUrl(page) {
				uni.navigateTo({
					url: page
				})
			},
			chooseProduct(product) {
				this.choosedProduct = product
				this.choosedSpec = product.specifications[0]

				this.showTag = true
			},
			add(index) {
				this.products[index].quantity++
				this.getCartData(index, this.products[index].specifications[0].id)
			},
			pev(index) {
				this.products[index].quantity--
				this.getCartData(index, this.products[index].specifications[0].id)
			},
			addSpec() {
				let had = false
				for (let i of this.carts) {
					if (i.specId == this.choosedSpec.id) {
						had = true
						i.quantity = this.quantity
					}
				}
				if (!had) {
					this.carts.push({
						specId: this.choosedSpec.id,
						specName: this.choosedSpec.name,
						cover: this.choosedProduct.cover,
						quantity: this.quantity,
						name: this.choosedProduct.name,
						price: this.choosedSpec.price
					})
				}
				uni.setStorageSync('carts', this.carts)
				uni.setTabBarBadge({
					index: 2,
					text: `${this.carts.length}`
				})
				this.showTag = false
				this.quantity = 1
			},
			getCartData(index, specId) {
				let product = this.products[index]
				let had = false
				let cartIndex = 0
				for (let i in this.carts) {
					if (this.carts[i].specId == specId) {
						had = true
						this.carts[i].quantity = this.products[index].quantity
						break
					}
				}
				if (!had) {
					this.carts.push({
						specId: specId,
						specName: this.products[index].specifications[0].name,
						cover: this.products[index].cover,
						quantity: this.products[index].quantity,
						name: this.products[index].name,
						price: this.products[index].specifications[0].price
					})
				}
				if (this.products[index].quantity <= 0) {
					this.carts.splice(cartIndex, 1)
				}
				if (this.carts.length > 0) {
					uni.setStorageSync('carts', this.carts)
					uni.setTabBarBadge({
						index: 2,
						text: `${this.carts.length}`
					})
				} else {
					uni.removeStorageSync('carts')
					uni.removeTabBarBadge({
						index: 2
					})
				}

			},
			//获取定位
			getAuthorizeInfo() { //1. uniapp弹窗弹出获取授权（地理，个人微信信息等授权信息）弹窗
				var _this = this;
				uni.authorize({
					scope: "scope.userLocation",
					success() { //1.1 允许授权
						console.log('有授权')
						_this.getLocationInfo();
					},
					fail() { //1.2 拒绝授权
						console.log('没有授权')
						uni.showModal({
							title: '温馨提示',
							content: '获取定位失败，为了给您提供更好的体验，请您点击右上角。。。，点击设置，微信信息设置选择允许,如有疑问请联系客服！',
							showCancel: false,
							confirmText: '我知道了',
							success: () => {
			
							}
						})
					}
				})
			},
			getLocationInfo() { //2. 获取地理位置
				var _this = this;
				uni.getLocation({
					type: 'wgs84',
					success(res) {
						console.log("你当前经纬度是：");
						console.log(res)
						let latitude, longitude;
						latitude = res.latitude.toString();
						longitude = res.longitude.toString();
					},
					fail() {
						// _this.noGps = true
						// uni.showModal({
						// 	title: '',
						// 	content: '定位失败，请打开您手机的GPS',
						// 	showCancel: false,
						// 	confirmColor: '确定',
						// 	success: ((data) => {
						// 		if (data.cancel) {}
						// 	})
						// })
					}
				});
			}
		}
	}
</script>

<style>
	.product-list {
		width: 50%;
	}

	.image-container {
		display: flex;
		/* 使用 Flexbox 布局 */
		justify-content: center;
		/* 水平居中 */
		align-items: center;
		/* 垂直居中 */
		height: 150px;
		/* 或者您想要的高度，这里假设是全屏高度 */
		width: 100%;
		/* 容器宽度为100% */
	}

	.image-a {
		max-width: 100%;
		/* 图片最大宽度不超过容器 */
		max-height: 100%;
		/* 图片最大高度不超过容器 */
		object-fit: cover;
	}

	.product-name {
		display: -webkit-box;
		-webkit-box-orient: vertical;
		-webkit-line-clamp: 3;
		overflow: hidden;
		text-overflow: ellipsis;
		font-size: 15px;
		height: 60px;
		color:#909399;
		padding:10px 0px 10px 0px;
	}

	.price {
		color: #ff9900;
		padding-top: 10px;
	}

	.title {
		color: #606266;
		padding: 10px 0px;
	}

	.date {
		color: #909399;
		font-size: 14px;
	}

	.activity-list {
		background-color: #f3f3f3;
		margin: 10px;
		border-radius: 5px;
		padding: 10px;
	}

	.spec-btn {
		background-color: #19be6b;
		font-size: 12px;
		color: #fff;
		padding: 3px 10px;
		border-radius: 14px;
	}

	.plus {
		width: 30px;
		height: 30px;
		background-color: #19be6b;
		border-radius: 50%;
		/* #ifndef APP-NVUE */
		display: flex;
		/* #endif */
		justify-content: center;
		align-items: center;
	}

	.container {
		display: flex;
		flex-wrap: wrap;
	}

	.item {
		margin: 5px;
	}

	.spec-active {
		font-size: 14px;
		padding: 3px 10px;
		border-radius: 5px;
		background-color: #19be6b;
		color: #fff
	}

	.spec {
		font-size: 14px;
		padding: 3px 10px;
		border-radius: 5px;
		background-color: #909399;
		color: #fff;
	}

	.minus {
		width: 30px;
		height: 30px;
		background-color: #fff;
		border-radius: 50%;
		/* #ifndef APP-NVUE */
		display: flex;
		/* #endif */
		justify-content: center;
		align-items: center;
	}
</style>